<template>
  <div class="edit-students">
    <el-drawer
      v-model="isShowEdit"
      title="新建/编辑"
      direction="rtl"
      size="50%"
      @close="closeEditDialog"
      @opened="loadContent"
      :close-on-click-modal="false"
    >
      <div style="margin-bottom: 30px; font-size: 18px">基本信息</div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="手机号码" prop="defaultMobile">
          <el-select
            v-model="ruleForm.defaultFamilyRel"
            placeholder="请选择手机持有人"
            style="width: 20%"
            clearable
          >
            <el-option
              v-for="(item, key) in parentList"
              :key="key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input v-model="ruleForm.defaultMobile" style="width: 80%" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="ruleForm.gender">
            <el-radio value="2">未知</el-radio>
            <el-radio value="0">男</el-radio>
            <el-radio value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="ruleForm.birthday"
            type="date"
            placeholder="请选择出生日期"
          />
        </el-form-item>
        <el-form-item label="就读学校">
          <el-input
            v-model="ruleForm.attendSchool"
            placeholder="请输入学校名称"
          />
        </el-form-item>
        <el-form-item label="当前年级">
          <el-select
            v-model="ruleForm.gradeId"
            placeholder="请选择学员来源"
            clearable
          >
            <el-option
              v-for="item in registrarStore.gradeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备用号码" prop="backMobile">
          <el-select
            v-model="ruleForm.backFamilyRel"
            placeholder="请选择手机持有人"
            style="width: 20%"
            clearable
          >
            <el-option
              v-for="(item, key) in parentList"
              :key="key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input v-model="ruleForm.backMobile" style="width: 80%" />
        </el-form-item>
        <!-- <div v-if="type === '编辑'">
          <el-form-item label="学号">
            <el-input v-model="ruleForm.idcard" disabled />
          </el-form-item>
        </div> -->
        <div style="margin-bottom: 30px; margin-top: 40px; font-size: 18px">
          其他信息
        </div>
        <el-form-item label="学员来源">
          <el-select
            v-model="ruleForm.joinWay"
            placeholder="请选择学员来源"
            clearable
          >
            <el-option
              v-for="item in registrarStore.joinWayList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="跟进人">
          <el-select
            v-model="ruleForm.counselorId"
            placeholder="请选择跟进人"
            clearable
          >
            <el-option
              v-for="item in registrarStore.peopleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="学员创建人">
          <el-select
            v-model="ruleForm.creator"
            placeholder="请选择学员创建人"
            clearable
          >
            <el-option
              v-for="item in followPeopleList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
              :disabled="!item.isJob"
            >
              {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学管师">
          <el-select
            v-model="ruleForm.managementId"
            placeholder="请选择学管师"
            clearable
          >
            <el-option
              v-for="item in managerPeopleList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
              :disabled="!item.isJob"
            >
              {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="ruleForm.remark" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="flex: auto">
          <el-button @click.prevent="cancelClick">取消</el-button>
          <el-button type="primary" @click.prevent="confirmClick"
            >保存</el-button
          >
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { editStudents } from "@/api/studentManagement/index.js";
import { ref, reactive, inject } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import useRegistrarStore from "@/store/modules/registrar";
import useUserStore from "@/store/modules/user";
import {
  getManagerList,
  getFollowPeopleList,
} from "@/api/studentManagement/index.js";
const { proxy } = getCurrentInstance();
const props = defineProps({
  isShowEdit: {
    type: Boolean,
    default: false,
  },
  students: {
    type: Object,
    default: {},
  },
  type: {
    type: String,
  },
  studentsId: {
    type: String,
  },
});
//获取仓库数据
const registrarStore = useRegistrarStore();
const userStore = useUserStore();
//跟进人&学员创建人
const followPeople = ref("");
const followPeopleList = ref([]);
const toFollowPeopleList = async () => {
  try {
    const res = await getFollowPeopleList({ pageNum: 1, pageSize: 9999 });
    if (res.code == 200) {
      followPeopleList.value = res.rows;
    }
  } catch (error) {
    console.error("获取学员创建人下拉列表失败:", error);
  }
};
onMounted(toFollowPeopleList);
const managerPeopleList = ref([]);
const managerPeople = ref("");

const toGetManagerList = async () => {
  try {
    const res = await getManagerList({ pageNum: 1, pageSize: 9999 });
    if (res.code == 200) {
      managerPeopleList.value = res.data;
    }
  } catch (error) {
    console.error("获取学管师下拉列表失败:", error);
  }
};
onMounted(toGetManagerList);

//创建家长下拉列表
const parentList = [
  {
    label: "无",
    value: "无",
  },
  {
    label: "本人",
    value: "本人",
  },
  {
    label: "爸爸",
    value: "爸爸",
  },
  {
    label: "妈妈",
    value: "妈妈",
  },
  {
    label: "爷爷",
    value: "爷爷",
  },
  {
    label: "奶奶",
    value: "奶奶",
  },
  {
    label: "外公",
    value: "外公",
  },
  {
    label: "外婆",
    value: "外婆",
  },
];

//处理日期和年龄
const calculateAge = (birthDate) => {
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDifference = today.getMonth() - birthDate.getMonth();
  // 如果还没有过生日，年龄减1
  if (
    monthDifference < 0 ||
    (monthDifference === 0 && today.getDate() < birthDate.getDate())
  ) {
    age--;
  }
  // return `${age}岁`
  return age;
};
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const formSize = ref("default");
// const ruleFormRef = ref({})
const ruleForm = ref({});
const initialFormData = ref({ ...props.students });
const loadContent = () => {
  {
    console.log("组件打开", props.type);
    if (props.type === "新建") {
      ruleForm.value = {
        creator: userStore.id,
        defaultFamilyRel: "无",
        backFamilyRel: "无",
        gender: "2",
      };
    } else if (props.type === "编辑") {
      ruleForm.value = { ...props.students };
    }
  }
};
watch(
  () => props.type,
  (newValue) => {
    if (newValue === "编辑") {
      console.log("编辑");
      console.log("ruleForm", ruleForm);

      // ruleForm.value = { ...props.students }
      // initialFormData.value = { ...props.students }
    }
    if (newValue === "新建") {
      console.log("新建", userStore.name);
      console.log("ruleForm", ruleForm);
      // ruleForm.creator.value = userStore.name
    }
  }
  // { immediate: true }
);

watch(
  () => props.students,
  (newValue) => {
    console.log("监听students");
    ruleForm.value = { ...newValue };
  }
  // { immediate: true }
);
//表单校验
const rules = reactive({
  name: [{ required: true, message: "请输入学生姓名", trigger: "blur" }],
  defaultMobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号(11位数字,以1开头,第二位是3到9之间的数字)",
      trigger: "blur",
    },
  ],
  backMobile: [
    // { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号(11位数字,以1开头,第二位是3到9之间的数字)",
      trigger: "blur",
    },
  ],
});

//重置表单
const ruleFormRef = ref(null);
const resetForm = () => {
  if (ruleFormRef.value) {
    ruleForm.value = { ...initialFormData.value };
    ruleFormRef.value.resetFields();
  }
};
//控制开关部分
const emit = defineEmits([
  "update:isShowEdit",
  "update:students",
  "update:searchStudent",
]);
const isShowEdit = ref(props.isShowEdit);
watch(
  () => props.isShowEdit,
  (newValue) => {
    isShowEdit.value = newValue;
  }
);
const studentId = ref(props.studentsId);
watch(
  () => props.studentsId,
  (newValue) => {
    studentId.value = newValue;
  }
);
//取消按钮
function cancelClick() {
  console.log("g取消");
  isShowEdit.value = false;
}
//关闭按钮
const closeEditDialog = () => {
  console.log("g关闭");
  resetForm();
  isShowEdit.value = false;
  emit("update:isShowEdit", false);
  // console.log('studentId.value',studentId.value);
  // console.log('props.studentsId',props.studentsId);
};
//确定按钮
function confirmClick() {
  ElMessageBox.confirm(`确定保存吗?`)
    .then(() => {
      // console.log('提交', ruleForm.value.birthday)
      submitForm();
    })
    .catch(() => {
      // catch error
    });
}
//提交表单
const submitForm = () => {
  proxy.$refs["ruleFormRef"].validate(async (valid) => {
    if (valid) {
      if (ruleForm.value.birthday) {
        ruleForm.value.age = calculateAge(new Date(ruleForm.value.birthday));
        ruleForm.value.birthday = formatDate(new Date(ruleForm.value.birthday));
      }
      ruleForm.value.defaultUser = {
        familyRel: ruleForm.value.defaultFamilyRel,
        mobile: ruleForm.value.defaultMobile,
      };
      if (ruleForm.value.backMobile) {
        ruleForm.value.backupUser = {
          familyRel: ruleForm.value.backFamilyRel,
          mobile: ruleForm.value.backMobile,
        };
      } else {
        ruleForm.value.backupUser = null;
      }
      try {
        const res = await editStudents(ruleForm.value);
        if (res.code == 200) {
          studentId.value = res.data;
          if (props.type === "编辑") {
            proxy.$modal.msgSuccess("学员信息编辑成功");
            // emit('update:students')
          } else if (props.type === "新建") {
            proxy.$modal.msgSuccess("新学员创建成功");
            // emit('update:searchStudent', res.data)
          }
          emit("update:students", res.data);

          isShowEdit.value = false;
        }
      } catch (error) {
        console.error("表单编辑失败:", error);
      }
    } else {
      proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
    }
  });
};
</script>

<style lang="scss" scoped>
// .edit-students{
//   padding: 10px 30%;
// }
</style>